package ch.zarzu.champions.builder;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileSystemWrapper {
    
    /**
     * Convenience method to easily write to a file.
     * 
     * @param   file    target file.
     * @param   string  string to be written.
     */
    public static void writeFile(File file, String string) {
        try {
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(string);
            fileWriter.close();
        } catch (IOException e) {
            ErrorLog.v("writing to " + file.getAbsolutePath(), e);
        }
    }
    
    /**
     * Convenience method to easily read a whole file.
     * 
     * @param f
     * @return
     */
    public static String readFile(File f) {
        StringBuffer input = new StringBuffer();
        
        try {
            FileInputStream fstream = new FileInputStream(f);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        
            while (br.ready()) {
                input.append(br.readLine()).append("\n");
            }
            //remove the last newline
            if(input.length() > 1) {
                input.delete(input.length() - 2, input.length());
            }
            br.close();
            in.close();
            fstream.close();
        } catch (FileNotFoundException e) {
            ErrorLog.v("reading from " + f.getAbsolutePath(), e);
        } catch (IOException e) {
            ErrorLog.v("reading from " + f.getAbsolutePath(), e);
        }
        
        return input.toString();
    }
    
    public static boolean deleteFile(File f) {
        return f.delete();
    }
}
